/*
 * @Description:
 * @Author: lcz
 * @LastEditors: lcz
 * @LastEditTime: 2025-06-04 13:22:54
 */
import React, { useState, useEffect, useRef, useCallback, useMemo } from "react";
import { Input } from "antd";
import { useSize } from "./utils/hooks";
import Highcharts from "highcharts/highstock.src";

import { commonEnabled, generateOHLCData } from "./utils";

import "./CandlestickChart.scss";
import "./utils/regsiter";
import type { AnnotationType, Annotation, TimeRange, Theme } from "./utils/interface";

// K线图组件
const CandlestickChart: React.FC = () => {
  const chartContainerRef = useRef<HTMLDivElement>(null);
  const chartRef = useRef<Highcharts.Chart | null>(null);

  useSize(chartRef);

  const [data, setData] = useState<[number, number, number, number, number][]>(generateOHLCData(365));
  const [timeRange, setTimeRange] = useState<TimeRange>("1Y");
  const [theme, setTheme] = useState<Theme>("light");
  const [isLoading, setIsLoading] = useState(false);

  const timeRanges: Record<TimeRange, number | null> = {
    "1M": 30,
    "3M": 90,
    "6M": 180,
    "1Y": 365,
    ALL: null
  };

  // 更改时间范围
  const changeTimeRange = (range: TimeRange) => {
    setIsLoading(true);
    setTimeRange(range);

    setTimeout(() => {
      const days = timeRanges[range];
      const newData = days ? generateOHLCData(days) : generateOHLCData(1000);
      setData(newData);
      setIsLoading(false);
    }, 500);
  };

  // 切换主题
  const toggleTheme = () => {
    setTheme(prev => (prev === "light" ? "dark" : "light"));
  };

  // 刷新数据
  const refreshData = () => {
    setIsLoading(true);

    setTimeout(() => {
      const newData = generateOHLCData(timeRanges[timeRange] || 365);
      setData(newData);
      setIsLoading(false);
    }, 800);
  };

  // 获取Highcharts配置
  const getChartOptions = useCallback(() => {
    const themeColors =
      theme === "light"
        ? {
            bg: "#FFFFFF",
            text: "#1E293B",
            grid: "#E2E8F0",
            axis: "#64748B",
            tooltipBg: "rgba(255, 255, 255, 0.8)",
            tooltipBorder: "#E2E8F0",
            navigatorMask: "rgba(59, 130, 246, 0.1)",
            scrollbar: {
              bar: "#E2E8F0",
              button: "#FFFFFF",
              track: "#F1F5F9"
            }
          }
        : {
            bg: "#1E293B",
            text: "#F8FAFC",
            grid: "#334155",
            axis: "#94A3B8",
            tooltipBg: "rgba(30, 41, 59, 0.8)",
            tooltipBorder: "#475569",
            navigatorMask: "rgba(59, 130, 246, 0.2)",
            scrollbar: {
              bar: "#334155",
              button: "#1E293B",
              track: "#1E293B"
            }
          };

    const baseOptions: Highcharts.Options = {
      ...commonEnabled,
      colors:
        theme === "light"
          ? [
              "#26A69A",
              "#EF5350",
              "#FFB74D",
              "#42A5F5",
              "#7E57C2",
              "#EC407A",
              "#5C6BC0",
              "#FF7043",
              "#66BB6A",
              "#26A69A"
            ]
          : [
              "#4DB6AC",
              "#EF5350",
              "#FFB74D",
              "#4FC3F7",
              "#9575CD",
              "#F06292",
              "#7986CB",
              "#FF8A65",
              "#81C784",
              "#4DB6AC"
            ],
      chart: {
        backgroundColor: themeColors.bg,
        style: {
          fontFamily: "Inter, system-ui, sans-serif"
        }
      },
      title: {
        text: "股票K线图",
        style: {
          color: themeColors.text
        }
      },
      subtitle: {
        text: "带技术指标的K线图分析",
        style: {
          color: themeColors.axis
        }
      },
      xAxis: {
        type: "datetime",
        labels: {
          style: {
            color: themeColors.axis
          }
        },
        gridLineColor: themeColors.grid
      },
      yAxis: [
        {
          // title: {
          //   text: '价格',
          //   style: {
          //     color: themeColors.axis
          //   }
          // },
          labels: {
            align: "right",
            x: -3,
            style: {
              color: themeColors.axis
            }
          },
          height: "70%",
          lineWidth: 0, //2
          resize: {
            enabled: true
          },
          gridLineColor: themeColors.grid
        },
        {
          // title: {
          //   text: '成交量',
          //   style: {
          //     color: themeColors.axis
          //   }
          // },
          labels: {
            align: "right",
            x: -3,
            style: {
              color: themeColors.axis
            }
          },
          top: "75%",
          height: "15%",
          offset: 0,
          lineWidth: 0, // 2
          gridLineColor: themeColors.grid
        }
      ],
      tooltip: {
        split: false, // 合并所有系列的提示到一个框中
        backgroundColor: themeColors.tooltipBg,
        borderColor: themeColors.tooltipBorder,
        style: {
          color: themeColors.text
        }
      },
      legend: {
        // 小圆点
        enabled: false,
        itemStyle: {
          color: themeColors.text
        },
        itemHoverStyle: {
          color: "#0EA5E9"
        },
        itemHiddenStyle: {
          color: themeColors.axis
        }
      },

      annotations: [
        {
          type: "fibonacci", // 斐波那契线
          typeOptions: {
            xAxis: 0,
            yAxis: 0,
            points: [
              [new Date("2023-01-01").getTime(), 120],
              [new Date("2023-06-01").getTime(), 180]
            ]
          }
        }
      ],
      navigation: {
        bindings: {
          text: {
            annotationsOptions: {
              labelOptions: {
                verticalAlign: "top",
                y: -11
              }
            }
          }
        }
      },
      navigator: {
        //滚动条
        enabled: false,
        height: 40,
        xAxis: {
          labels: {
            style: {
              color: themeColors.axis
            }
          },
          gridLineColor: themeColors.grid
        },
        maskFill: themeColors.navigatorMask,
        handles: {
          backgroundColor: themeColors.bg,
          borderColor: themeColors.grid
        }
      },
      scrollbar: {
        //一条横线不知道干嘛的
        enabled: false,
        barBackgroundColor: themeColors.scrollbar.bar,
        barBorderRadius: 7,
        barBorderWidth: 0,
        buttonBackgroundColor: themeColors.scrollbar.button,
        buttonBorderColor: themeColors.grid,
        buttonBorderWidth: 1,
        buttonArrowColor: themeColors.axis,
        rifleColor: themeColors.axis,
        trackBackgroundColor: themeColors.scrollbar.track,
        trackBorderColor: themeColors.grid,
        trackBorderWidth: 1,
        trackBorderRadius: 8
      },

      series: []
    };

    return baseOptions;
  }, [theme]);

  // 创建图表
  useEffect(() => {
    if (!chartContainerRef.current) return;

    // 销毁现有图表
    if (chartRef.current) {
      chartRef.current.destroy();
    }

    // 创建新图表
    const options = getChartOptions();

    // 添加蜡烛图系列
    options.series = [
      {
        type: "candlestick",
        name: "价格",
        data: data,
        color: "#EF5350",
        upColor: "#26A69A",
        lineColor: "#B71C1C",
        upLineColor: "#004D40",
        tooltip: {
          valueDecimals: 2
        },
        dataGrouping: {
          units: [
            ["day", [1]],
            ["week", [1]],
            ["month", [1, 3, 6]]
          ]
        }
      },
      {
        type: "column",
        name: "成交量",
        data: data.map(([time, open, high, low, close]) => {
          const volume = Math.floor(Math.random() * 1000000);
          return [time, volume];
        }),
        yAxis: 1,
        color: "#42A5F5",
        dataGrouping: {
          units: [
            ["day", [1]],
            ["week", [1]],
            ["month", [1, 3, 6]]
          ]
        }
      }
    ];

    // 创建Highcharts实例
    chartRef.current = Highcharts.stockChart(chartContainerRef.current, options);
    console.log(chartRef.current, "chartRef.current");
    // 绑定图表点击事件
    if (chartRef.current) {
      chartRef.current.container.addEventListener("click", handleChartClick);
      console.log("zljc");
    }

    // 清理函数
    return () => {
      if (chartRef.current) {
        chartRef.current.destroy();
        chartRef.current?.container?.removeEventListener("click", handleChartClick);
        chartRef.current = null;
      }
    };
  }, [chartContainerRef, getChartOptions]);

  // add code
  const annotationsContainerRef = useRef<HTMLDivElement>(null);
  const [activeTool, setActiveTool] = useState<AnnotationType | null>(null);
  const [annotations, setAnnotations] = useState<Annotation[]>([]);
  const [isEditing, setIsEditing] = useState(false);
  const [tempAnnotation, setTempAnnotation] = useState<Annotation | null>(null);

  const activeToolRef = useRef(activeTool);
  useEffect(() => {
    activeToolRef.current = activeTool;
  }, [activeTool]);
  // 处理图表点击
  const handleChartClick = (e: MouseEvent) => {
    if (!chartRef.current || !activeTool || isEditing) return;
    console.log("click draw");
    // 获取图表容器位置
    const containerRect = chartContainerRef.current!.getBoundingClientRect();
    const x = e.clientX - containerRect.left;
    const y = e.clientY - containerRect.top;

    // 转换为数据坐标
    const chart = chartRef.current;
    const dataX = chart.xAxis[0].toValue(x);
    const dataY = chart.yAxis[0].toValue(y);
    console.log(dataX, dataY, activeToolRef.current, "3222");
    // 根据当前工具创建不同类型的标注
    switch (activeToolRef.current) {
      case "text":
        // 创建文本标注
        createTextAnnotation(dataX, dataY, x, y);
        break;
      case "line":
        // 开始创建线条标注
        setTempAnnotation({
          id: `temp-${Date.now()}`,
          type: "line",
          position: { x: dataX, y: dataY },
          pixelPosition: { x, y },
          startPosition: { x: dataX, y: dataY }
        });
        break;
      case "rect":
        // 开始创建矩形标注
        setTempAnnotation({
          id: `temp-${Date.now()}`,
          type: "rect",
          position: { x: dataX, y: dataY },
          pixelPosition: { x, y },
          startPosition: { x: dataX, y: dataY }
        });
        break;
      case "fibonacci":
        // 创建斐波那契线(使用Highcharts内置)
        createFibonacciAnnotation(dataX, dataY);
        break;
    }
  };

  const createTextAnnotation = (dataX: number, dataY: number, pixelX: number, pixelY: number) => {
    setIsEditing(true);

    // 创建临时标注对象
    const newAnnotation: Annotation = {
      id: `annotation-${Date.now()}`,
      type: "text",
      position: { x: dataX, y: dataY },
      pixelPosition: { x: pixelX, y: pixelY },
      content: "输入标注文本"
    };

    // 添加到状态
    setAnnotations(prev => [...prev, newAnnotation]);

    // 延迟聚焦到输入框
    setTimeout(() => {
      const inputElement = document.getElementById(`annotation-input-${newAnnotation.id}`);
      inputElement?.focus();
    }, 100);
  };

  // 更新文本标注内容
  const updateTextAnnotation = (id: string, content: string) => {
    setAnnotations(prev => prev.map(annotation => (annotation.id === id ? { ...annotation, content } : annotation)));
  };

  // 完成文本编辑
  const finishEditing = (id: string) => {
    setIsEditing(false);
    setActiveTool(null);
  };

  // 创建斐波那契线
  const createFibonacciAnnotation = (dataX: number, dataY: number) => {
    if (!chartRef.current) return;

    // 使用Highcharts内置斐波那契线工具
    chartRef.current.addAnnotation({
      type: "fibonacci",
      typeOptions: {
        xAxis: 0,
        yAxis: 0,
        points: [
          { x: dataX, y: dataY },
          { x: dataX + 30 * 24 * 3600 * 1000, y: dataY + 50 } // 假设终点在30天后，价格上涨50
        ]
      }
    });
  };

  // 渲染标注元素
  const renderAnnotations = () => {
    return annotations.map(annotation => {
      switch (annotation.type) {
        case "text":
          return (
            <div
              key={annotation.id}
              className='chart-annotation text-annotation'
              style={{
                left: `${annotation.pixelPosition.x}px`,
                top: `${annotation.pixelPosition.y}px`,
                position: "absolute"
              }}
            >
              {isEditing && annotation.id === annotations[annotations.length - 1].id ? (
                <Input
                  id={`annotation-input-${annotation.id}`}
                  value={annotation.content || ""}
                  onChange={e => updateTextAnnotation(annotation.id, e.target.value)}
                  onBlur={() => finishEditing(annotation.id)}
                  onPressEnter={() => finishEditing(annotation.id)}
                  className='annotation-input'
                  placeholder='输入标注...'
                />
              ) : (
                <div className='annotation-text'>{annotation.content}</div>
              )}
            </div>
          );
        case "line":
          if (!annotation.startPosition || !annotation.endPosition) return null;

          // 计算线条长度和角度
          const start = annotation.startPosition;
          const end = annotation.endPosition;
          const dx = end.x - start.x;
          const dy = end.y - start.y;
          const length = Math.sqrt(dx * dx + dy * dy);
          const angle = (Math.atan2(dy, dx) * 180) / Math.PI;

          return (
            <div
              key={annotation.id}
              className='chart-annotation line-annotation'
              style={{
                left: `${annotation.pixelPosition.x}px`,
                top: `${annotation.pixelPosition.y}px`,
                position: "absolute",
                width: `${length}px`,
                height: "2px",
                transformOrigin: "0 50%",
                transform: `rotate(${angle}deg)`,
                backgroundColor: "#FF0000"
              }}
            />
          );
        case "rect":
          if (!annotation.startPosition || !annotation.endPosition) return null;

          // 计算矩形尺寸
          const rectStart = annotation.startPosition;
          const rectEnd = annotation.endPosition;
          const rectX = Math.min(rectStart.x, rectEnd.x);
          const rectY = Math.min(rectStart.y, rectEnd.y);
          const rectWidth = Math.abs(rectEnd.x - rectStart.x);
          const rectHeight = Math.abs(rectEnd.y - rectStart.y);

          // 转换为像素坐标
          const chart = chartRef.current;
          if (!chart) return null;

          const pixelX = chart.xAxis[0].toPixels(rectX);
          const pixelY = chart.yAxis[0].toPixels(rectY);
          const pixelWidth = chart.xAxis[0].toPixels(rectX + rectWidth) - pixelX;
          const pixelHeight = chart.yAxis[0].toPixels(rectY) - chart.yAxis[0].toPixels(rectY + rectHeight);

          return (
            <div
              key={annotation.id}
              className='chart-annotation rect-annotation'
              style={{
                left: `${pixelX}px`,
                top: `${pixelY}px`,
                position: "absolute",
                width: `${pixelWidth}px`,
                height: `${pixelHeight}px`,
                border: "2px solid #00FF00",
                backgroundColor: "rgba(0, 255, 0, 0.1)"
              }}
            />
          );
        default:
          return null;
      }
    });
  };

  return (
    <div className={`candlestick-chart ${theme}-theme`}>
      <div className='chart-container'>
        {/* 控制工具栏 */}
        <div className='control-bar'>
          <div className='button-group'>
            <button className='btn-toggle' onClick={refreshData}>
              <i className='fa fa-refresh mr-1'></i> 刷新
            </button>
            <button className='btn-toggle' onClick={toggleTheme}>
              <i className={`fa ${theme === "light" ? "fa-moon-o" : "fa-sun-o"} mr-1`}></i>
              {theme === "light" ? "暗色" : "亮色"}
            </button>
          </div>

          <div className='time-range-selector'>
            <span className='label'>时间范围:</span>
            {Object.keys(timeRanges).map(range => (
              <button
                key={range}
                className={`btn-toggle ${timeRange === range ? "active" : ""}`}
                onClick={() => changeTimeRange(range as TimeRange)}
              >
                {range}
              </button>
            ))}
          </div>
        </div>

        {/* 图表区域 */}
        <div className='chart-wrapper'>
          {isLoading && (
            <div className='loading-overlay'>
              <div className='spinner'></div>
              <p className='loading-text'>加载数据中...</p>
            </div>
          )}
          <div ref={chartContainerRef} className='w-full h-full'></div>
          {/* 渲染容器 */}
          <div
            ref={annotationsContainerRef}
            className='annotations-container'
            style={{
              position: "absolute",
              top: 0,
              left: 0,
              width: "100%",
              height: "100%",
              // pointerEvents: activeTool ? "none" : "auto"
              // pointerEvents: "none"
            }}
          >
            {renderAnnotations()}
          </div>
        </div>
        {/* 标注工具 */}
        <div className='annotation-tools'>
          <button
            className={`annotation-btn ${activeTool === "text" ? "active" : ""}`}
            onClick={() => setActiveTool("text")}
          >
            文本
          </button>
          <button
            className={`annotation-btn ${activeTool === "line" ? "active" : ""}`}
            onClick={() => setActiveTool("line")}
          >
            直线
          </button>
          <button
            className={`annotation-btn ${activeTool === "rect" ? "active" : ""}`}
            onClick={() => setActiveTool("rect")}
          >
            矩形
          </button>
          <button
            className={`annotation-btn ${activeTool === "fibonacci" ? "active" : ""}`}
            onClick={() => setActiveTool("fibonacci")}
          >
            斐波那契
          </button>
          <button className='annotation-btn' onClick={() => setAnnotations([])}>
            清除
          </button>
          <button onClick={() => setActiveTool(null)}>取消选择</button>
        </div>
        {/* 数据统计区域 */}
        <div className='stats-section'>
          <div className='stats-grid'>
            <div className='stat-card'>
              <p className='stat-title'>当前价格</p>
              <p className='stat-value text-primary'>¥{data[data.length - 1][4].toFixed(2)}</p>
            </div>
            <div className='stat-card'>
              <p className='stat-title'>今日涨跌</p>
              <p className='stat-value text-success'>+¥2.34 (2.4%)</p>
            </div>
            <div className='stat-card'>
              <p className='stat-title'>最高价</p>
              <p className='stat-value'>¥{data[data.length - 1][2].toFixed(2)}</p>
            </div>
            <div className='stat-card'>
              <p className='stat-title'>最低价</p>
              <p className='stat-value'>¥{data[data.length - 1][3].toFixed(2)}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default CandlestickChart;
